<template>
    <div class="boxContentCss">
        <el-form ref="formRef" :model="form" label-position="right" label-width="auto">
            <EdCreateCard title="商品信息">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <div class="zh_flex">
                    <el-row class="width-100">
                        <el-col :span="12">
                            <el-form-item label="商品名称" prop="productName" :rules="$validate.validates({required:true,msg:'不能为空',type: 'producetName'})">
                                <el-input class="flex-input" placeholder="请输入商品名称" v-model="form.productName" maxlength="50"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="12">
                            <el-form-item label="商品类别" prop="categoryId" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <!-- <EdSelect v-model="form.categoryId" :selectParams="selectGoodsType"></EdSelect> -->
                                <EdCascader v-model="form.categoryId" :cascaderParams="selectGoodsType"></EdCascader>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="12">
                            <el-form-item label="商品标签" prop="tag">
                                <EdSelect v-model="form.tag" :selectParams="selectTagType"></EdSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                     <el-row class="width-100">
                        <el-col :span="12">
                            <el-form-item class="style_money" label="商品售价" prop="sell_price" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-col :span="24" style="margin-bottom: 10px">
                                    <el-checkbox :value="form.money.length>0?true:false" class="priceCheck_1" @change="checkChange_money">
                                        <el-input v-model="form.money" @blur="inputBlur" class="price_input_1" maxlength="11">
                                            <i slot="suffix" style="font-style:normal;">元</i>
                                        </el-input>
                                    <span v-show="form.money.length>0&&(!(regFloatTwo.test(form.money))||form.money==0)" style="color: #F56C6C;display: inline-block;margin-left: 5px;">商品售价为小于9位的正数，且最多保留两位有效小数！</span>
                                    </el-checkbox>
                                </el-col>
                                <el-col :span="24" style="margin-bottom: 10px">
                                    <el-checkbox :value="form.point.length>0?true:false" class="priceCheck_1" @change="checkChange_point">
                                        <el-input v-model="form.point" @blur="inputBlur" class="price_input_1" maxlength="8">
                                            <i slot="suffix" style="font-style:normal;">积分</i>
                                        </el-input>
                                        <span v-show="form.point&&!(regPoint.test(form.point))" style="display: inline-block; margin-left: 5px; color: #F56C6C">积分为小于9位的正整数！</span>
                                    </el-checkbox>
                                </el-col>
                                <el-col :span="24" style="margin-bottom: 10px" class="moneyStyle">
                                    <el-checkbox :value="form.moneyPoint.money.length>0&&form.moneyPoint.point.length>0?true:false" @change="checkChange_moneyPoint">
                                        <el-input v-model="form.moneyPoint.money" @blur="inputBlur" class="price_input_1" maxlength="11">
                                            <i slot="suffix" style="font-style:normal;">元</i>
                                        </el-input>
                                        <i class="el-icon-plus" style="padding-top: 15px; color: #909399"></i>
                                        <el-input v-model="form.moneyPoint.point" @blur="inputBlur" class="price_input_1" maxlength="8">
                                            <i slot="suffix" style="font-style:normal;">积分</i>
                                        </el-input>
                                        <span v-show="form.moneyPoint.money.length>0&&(!(regFloatTwo.test(form.moneyPoint.money))||form.moneyPoint.money==0)" style="color: #F56C6C;;margin-left: 5px;">商品售价为小于9位的正数，且最多保留两位有效小数！</span>
                                        <span v-show="form.moneyPoint.point&&!(regPoint.test(form.moneyPoint.point))" style="color: #F56C6C;margin-left: 5px;">积分为小于9位的正整数！</span>
                                    </el-checkbox>
                                </el-col>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="5">
                            <el-form-item label="商品库存" prop="stock" :rules="$validate.validates({required:true,msg:'不能为空', type: 'stock'})">
                                <el-input class="flex-input" v-model="form.stock">
                                    <!-- <template slot="append">件</template> -->
                                    <i slot="suffix" style="font-style:normal;margin-right: 10px;">件</i>
                                </el-input>
                                <!-- <span v-show="form.stock&&!(/^\d*$/.test(form.stock))" style="color: #F56C6C;margin-left: 5px">请输入整数</span> -->
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="活动时间" prop="activityTime">
                                <!-- <EdDateTimeRange ref="timeRange" @emit-echo-time-range="emitEchoTimeDate($event, 'activityTime')"></EdDateTimeRange> -->
                                <EdDateTimePickerRange  :pickerOptions="'days'"  v-model="form.activityTime"  @emit-echo-time-range="emitEchoTimeDate($event, 'activityTime')" :pickerParams="pickerRangeParams"></EdDateTimePickerRange>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="24">
                            <el-form-item label="商品图片" prop="pics" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-upload
                                    class="upload-img"
                                    accept="image/*"
                                    :action="action"
                                    list-type="picture-card"
                                    :limit="5"
                                    :multiple="true"
                                    :file-list="fileList"
                                    :before-upload="beforeImgUpload"
                                    :on-preview="handleImgPreview"
                                    :on-success="handleImgSuccess"
                                    :on-remove="handleImgRemove">
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                            <el-dialog :visible.sync="dialogVisible">
                                <img width="100%" :src="dialogImageUrl" alt="">
                            </el-dialog>
                            <p class="labelFont">请上传2M以内，大小430px*430px,格式为jpeg、jpg、png、gif的图片，至多5张</p>
                        </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="12">
                            <el-form-item label="商品详情" prop="description" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <EdTinymce ref="EdTinymce" v-model="form.description"></EdTinymce>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <el-form-item class="form_btns">
                    <el-button class="ed-button ed_black-bottom" @click="onSubmit('formRef')" :loading="disabled">确定</el-button>
                    <el-button class="ed-button ed_white_bottom" @click="$utilsSet.goBack($router)">取消</el-button>
                </el-form-item>
            </EdCreateCard>
        </el-form>
    </div>
</template>

<script>
    import EdTinymce from 'src/components/EdTinymce.vue'
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import EdDateTimeRange from 'src/components/EdDateTimeRange.vue'
    import EdDateTimePickerRange from 'src/components/EdDateTimePickerRange.vue'
    import EdSelect from 'src/components/EdSelect.vue'
    import EdCascader from 'src/components/EdCascader.vue'
    import { defineComponent } from 'vue'
    import { commodityInfo, commodityAdd, commodityUpdate, getResourceType, getTagList } from "./api";
    export default defineComponent({
        name: "companyCreate",
        components: { EdCreateCard, EdDateTimeRange, EdSelect, EdTinymce, EdCascader, EdDateTimePickerRange },
        data(){
            return{
                form:{
                    productName: '',
                    categoryId: '',
                    tag: '',
                    // 商品售价
                    money: '',
                    point: '',
                    moneyPoint: {
                        money: '',
                        point: '',
                    },
                    sell_price: [],

                    stock: '',
                    activityTime: '',
                    activityStartTime: '',
                    activityEndTime: '',
                    pics: [],
                    description: '',
                },
                pickerParams:{
                    valueFormat:"yyyy-MM-dd"
                },
                pickerRangeParams:{
                    valueFormat:"yyyy-MM-dd HH:mm"
                },
                disabled:false,
                isUpdate: false,
                fileList: [],
                action: '',
                dialogImageUrl: '',
                dialogVisible: false,
                selectGoodsType:{
                    placeholder:"请选择商品类别",
                    options: [],
                    props: { value: 'code', label: 'categoryName', checkStrictly: false, emitPath: false }
                },
                selectTagType:{
                    placeholder:"请选择商品标签",
                    options: [
                        // { value: '1', label: '物业费折扣券' },
                        // { value: '2', label: '母婴' },
                    ],
                    props: { value: 'id', label: 'tagName' },
                },
                selectSource:{
                    placeholder:"请选择来源",
                    options: [
                        { value: '1', label: '轻喜到家' },
                        { value: '2', label: '天仙配' },
                        { value: '3', label: '卡券平台' },
                    ],
                },
                canRefundList: [
                    { value: '0', label: '不支持' },
                    { value: '1', label: '支持' },
                ],
                canSendList: [
                    { value: '0', label: '否' },
                    { value: '1', label: '是' },
                ],
                goodsInfoList: [
                    { value: '1', label: '输入地址' },
                    { value: '2', label: '输入图文' },
                ],
                check_money: false,
                check_point: false,
                check_moneyPoint: false,
                point_warning_show: false,
                point_warning_show_2: false,
                // 正数、两位有效小数校验
                regFloatTwo: /^(([1-9][0-9]{0,7})|([0]\.\d{1,2})|([1-9][0-9]{0,7}\.\d{1,2}))$/,
                // 积分 小于9位的正整数
                regPoint: /^[1-9]\d{0,7}$/,
                uploadStyle: 'inline-block'
            }
        },
        activated(){
            getResourceType({pageSize: 999999}).then(res=>{
                this.selectGoodsType.options = res.data;
            })
            // 标签
             getTagList({pageSize: 999999}).then(res=>{
                this.selectTagType.options = res.data.records;
            })
            this.action = this.$baseApi + "/infra/file/upload";
            if(this.$route.query.id){
                // 编辑 
                this.isUpdate = true;
                this.commodityInfo();
            }else {
              
            }
        },
        deactivated(){
            this.form={
                productName: '',
                categoryId: '',
                tag: '',
                // 商品售价
                money: '',
                point: '',
                moneyPoint: {
                    money: '',
                    point: '',
                },
                sell_price: [],

                stock: '',
                activityTime: '',
                activityStartTime: '',
                activityEndTime: '',
                pics: [],
                description: '',
            }
            this.fileList = [];
            // this.$refs.timeRange.reset();
            // 清空editor的缓存
            if(this.$refs.EdTinymce) this.$refs.EdTinymce.$children[0].cache = '';
            this.disabled = false;
            this.$refs.formRef.resetFields()
            this.uploadStyle = 'inline-block'
        },
        methods:{
            commodityInfo(){
                commodityInfo({id:this.$route.query.id}).then(response => {
                    if(response.success == true) {
                        this.form = {
                            ...this.form,
                            id: response.data.id,
                            productName: response.data.productName,
                            categoryId: response.data.categoryId&&response.data.categoryId.toString(),
                            tag: response.data.tag&&response.data.tag.toString(),
                            money: response.data.money !=null ? response.data.money.toString() : '',
                            point: response.data.point !=null ? response.data.point.toString() : '',
                            // moneyPoint: response.data.moneyPoint,
                            moneyPoint: {
                                money: response.data.moneyPoint.money != null ? response.data.moneyPoint.money.toString() : '',
                                point: response.data.moneyPoint.point != null ? response.data.moneyPoint.point.toString() : '',
                            },
                            stock: response.data.stock,
                            activityStartTime: response.data.activityStartTime,
                            activityEndTime: response.data.activityEndTime,
                            activityTime: response.data.activityStartTime&&[response.data.activityStartTime, response.data.activityEndTime],
                            pics: response.data.pics,
                            description: response.data.description,
                        };

                        this.form.sell_price.push(response.data.money&&response.data.money, response.data.point&&response.data.point, response.data.moneyPoint.money&&response.data.moneyPoint.money);
                        // this.$refs.timeRange.time = response.data.activityStartTime&&[response.data.activityStartTime, response.data.activityEndTime];
                        this.fileList = response.data.pics.map(v=>{
                            return {url: v}
                        })
                    }
                })
            },
            emitEchoTimeDate($event, name){
                // $event 子组件$emit传的参数 
                // this.form['activityTime'] = $event;
                this.form['activityStartTime']=$event['startTime'];
                this.form['activityEndTime']=$event['endTime'];
            },
            onSubmit(formName){
                this.$refs[formName].validate((valid) => {
                    if(valid){
                        this.disabled = true;
                        if(this.form.money.length==0 && this.form.point.length==0 && this.form.moneyPoint.money.length==0) {
                            this.disabled = false;
                            return this.$message.error({ message: '请填写商品售价！', center: true });
                        }else if(this.form.moneyPoint.money.length!=0&&this.form.moneyPoint.point.length==0 || this.form.moneyPoint.money.length==0&&this.form.moneyPoint.point.length!=0){
                            this.disabled = false;
                            return this.$message.error({ message: '商品售价选择金额加积分时，两者都必填！', center: true });
                        }else if(this.form.money.length>0&&(!(this.regFloatTwo.test(this.form.money))||this.form.money==0) || this.form.moneyPoint.money.length>0&&(!(this.regFloatTwo.test(this.form.moneyPoint.money))||this.form.moneyPoint.money==0)){
                            // 售价：整数、两位小数
                            this.disabled = false
                            return this.$message.error({ message: '商品售价为小于9位的正数，且最多保留两位有效小数！', center: true })
                        }else if( this.form.point&&!(this.regPoint.test(this.form.point)) || this.form.moneyPoint.point&&!(this.regPoint.test(this.form.moneyPoint.point))){
                            // 积分为小于9位的正整数
                            this.disabled = false
                            return this.$message.error({ message: '积分为小于9位的正整数！', center: true })
                        }

                        let query = this.form.copy();
                        delete query['sell_price'];
                        delete query['activityTime'];
                        // console.log('form--->', this.form)
                        // return
                        let funcApi = this.isUpdate ? commodityUpdate : commodityAdd;
                        funcApi(query).then(response => {
                            if(response.success == true) {
                                this.disabled = false;
                                this.$message.success({
                                    message: '保存成功',
                                    center: true,
                                    duration: 2000,
                                });
                                if(this.$route.query.type !=0){
                                    window.setTimeout(() => {
                                        this.$utilsSet.goBack(this.$router);
                                    }, 600)
                                }
                            }else {
                                this.disabled = false
                            }
                        }).catch(()=>{
                            this.disabled = false
                        })
                    }
                })
            },
             // 图片 上传前
            beforeImgUpload(file){
                // console.log('before-->', file)
                const fileType = file.name.split('.');
                const fileDate = fileType.slice(-1);
                // if (['jpeg', 'jpg', 'png', 'gif'].indexOf(fileDate[0]) < 0) {
                // if (['jpeg', 'jpg', 'png', 'gif'].indexOf(file.type.split('/')[1]) < 0) {
                //     this.$message.error({ message: '仅支持格式：jpeg、jpg、png、gif!', center: true });
                //     return false
                // }
                // if (this.fileList.length > 5) {
                //     this.$message.error('最多上传三张图片！')
                //     return false;
                // }
                const isLt5M = file.size / 1024 /1024 < 2;
                if (!isLt5M) {
                    this.$message.error({ message: '上传文件大小不能超过 2MB!', center: true });
                }
                return isLt5M;
            },
            // 图片 上传成功
            handleImgSuccess(response, file, fileList){
                let res = file.response;
                if(res&&res.success == true){
                   this.form.pics.push(res['data'])
                }
                this.uploadStyle = fileList.length==5?'none':'inline-block'
            },
            // 图片 删除
            handleImgRemove(file, fileList) {
                this.form.pics = fileList&&fileList.map(v=>{
                    return v['response']? v['response']['data'] : v['url']
                })
                this.uploadStyle = fileList.length==5?'none':'inline-block'
            },
            // 图片 预览
            handleImgPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            // 编辑 checkbox - change
            checkChange_money(val){
                if(!val) this.form.money = '';
            },
            checkChange_point(val){
                if(!val) this.form.point = '';
            },
            checkChange_moneyPoint(val){
                if(!val) this.form.moneyPoint = {money: '', point: ''};
            },
            inputBlur(e){
                if(e.target.value) this.form.sell_price.push(e.target.value);
            },
            inputBlur_1(e){
                if(e.target.value) {
                    let reg = /^[1-9]\d*$/;
                    const is_true = reg.test(e.target.value)
                    if(!is_true){
                        // 积分为整数
                        this.point_warning_show = true
                    }else{
                    this.form.sell_price.push(e.target.value);
                    this.point_warning_show = false
                    }
                }else{
                    this.point_warning_show = false
                }
            },
            inputBlur_2(e){
                if(e.target.value) {
                    let reg = /^[1-9]\d*$/;
                    const is_true = reg.test(e.target.value)
                    if(!is_true){
                        // 积分为整数
                        this.point_warning_show_2 = true
                    }else{
                    this.form.sell_price.push(e.target.value);
                    this.point_warning_show_2 = false
                    }
                }else{
                    this.point_warning_show_2 = false
                }
            },
        }
    })
</script>

<style scoped lang="scss">
    :deep .el-form{
        .el-input{
            width: 100% !important;
        }
        .el-select{
            width: 100% !important;
        }
        .el-date-editor{
            width: 100% !important;
        }
        // .priceCheck_1 .el-checkbox__input{
        //     margin-top: 15px;
        // }
        .price_input_1.el-input{
            width: 230px!important;
        }

        .el-checkbox.is-checked{
            .el-checkbox__input{
                .el-checkbox__inner{
                    border-color: #EED096;
                    background: #EED096;
                }
            }
            .el-checkbox__label{
                color: #EED096;
            }
        }
        .el-checkbox{
            .el-checkbox__input.is-focus{
                .el-checkbox__inner{
                    border-color: #EED096;
                }
            }
            .el-checkbox__label{
                color: #EED096;
            }
        }

        .el-checkbox{
            .el-checkbox__input{
                .el-checkbox__inner:hover{
                    border-color: #EED096;
                }
            }
        }   
        .el-input-group__append{
            width: 55px !important;
            padding: 0 !important;
            text-align: center !important;
        }
        .style_money{
            .el-input__suffix-inner{
                display: inline-block;
                margin-top: 10px;
                margin-right: 10px;
            }
        }
        .upload-img .el-upload{
            display: v-bind(uploadStyle)
        }
    }
    .labelFont{
        font-family: 'Noto Sans SC';
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        color: #989898;
    }
</style>